/**
 * 图片懒加载组件
 * 优化图片加载性能，减少页面切换时的资源消耗
 */

Component({
  properties: {
    src: {
      type: String,
      value: ''
    },
    placeholder: {
      type: String,
      value: '/assets/common/img_loading.png'
    },
    mode: {
      type: String,
      value: 'aspectFit'
    },
    lazy: {
      type: Boolean,
      value: true
    },
    fadeIn: {
      type: Boolean,
      value: true
    }
  },

  data: {
    loaded: false,
    error: false,
    showPlaceholder: true,
    imageSrc: ''
  },

  lifetimes: {
    attached() {
      if (this.properties.lazy) {
        this.initLazyLoad();
      } else {
        this.setData({
          imageSrc: this.properties.src
        });
      }
    }
  },

  observers: {
    'src': function(newSrc) {
      if (newSrc && !this.properties.lazy) {
        this.setData({
          imageSrc: newSrc,
          loaded: false,
          error: false
        });
      }
    }
  },

  methods: {
    /**
     * 初始化懒加载
     */
    initLazyLoad() {
      // 使用 Intersection Observer 监听元素是否进入视口
      if (wx.createIntersectionObserver) {
        const observer = wx.createIntersectionObserver(this, {
          thresholds: [0.1], // 当元素10%可见时触发
          rootMargin: '50px' // 提前50px开始加载
        });

        observer.relativeToViewport().observe('.lazy-image-container', (res) => {
          if (res.intersectionRatio > 0 && !this.data.loaded && !this.data.error) {
            this.loadImage();
            observer.disconnect();
          }
        });
      } else {
        // 降级处理：直接加载
        this.loadImage();
      }
    },

    /**
     * 加载图片
     */
    loadImage() {
      const { src } = this.properties;
      
      if (!src) {
        this.setData({ error: true });
        return;
      }

      // 预加载图片
      wx.getImageInfo({
        src: src,
        success: (res) => {
          this.setData({
            imageSrc: src,
            loaded: true,
            showPlaceholder: false
          });
          
          // 触发加载完成事件
          this.triggerEvent('load', {
            width: res.width,
            height: res.height
          });
        },
        fail: (error) => {
          console.error('图片加载失败:', error);
          this.setData({
            error: true,
            showPlaceholder: false
          });
          
          // 触发加载失败事件
          this.triggerEvent('error', error);
        }
      });
    },

    /**
     * 图片点击事件
     */
    onImageTap() {
      this.triggerEvent('tap');
    },

    /**
     * 重试加载
     */
    retryLoad() {
      this.setData({
        error: false,
        showPlaceholder: true
      });
      this.loadImage();
    }
  }
});
